<template>
  <div class="profile-container">
    <div class="profile-header">
      <h1>个人中心</h1>
      <p>管理您的个人信息和账户设置</p>
    </div>
    
    <div class="profile-content">
      <!-- 头像设置区域 -->
      <n-card title="头像设置" class="avatar-section">
        <div class="avatar-container">
          <div class="avatar-preview">
            <img 
              v-if="userInfo.avatar" 
              :src="userInfo.avatar" 
              :alt="userInfo.username"
              :class="['avatar-img', avatarShape]"
            />
            <div 
              v-else 
              :class="['avatar-placeholder', avatarShape]"
            >
              {{ userInfo.username?.charAt(0).toUpperCase() }}
            </div>
            
            <div class="avatar-overlay" @click="showAvatarUpload = true">
              <n-icon size="24"><CameraOutline /></n-icon>
            </div>
          </div>
          
          <div class="avatar-controls">
            <n-button-group>
              <n-button 
                :type="avatarShape === 'circle' ? 'primary' : 'default'"
                @click="avatarShape = 'circle'"
              >
                圆形
              </n-button>
              <n-button 
                :type="avatarShape === 'square' ? 'primary' : 'default'"
                @click="avatarShape = 'square'"
              >
                方形
              </n-button>
            </n-button-group>
            
            <n-button type="primary" @click="showAvatarUpload = true">
              <template #icon>
                <n-icon><CloudUploadOutline /></n-icon>
              </template>
              上传头像
            </n-button>
          </div>
        </div>
      </n-card>
      
      <!-- 基本信息 -->
      <n-card title="基本信息" class="info-section">
        <n-form 
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-placement="left"
          label-width="100px"
        >
          <n-form-item label="用户名" path="username">
            <n-input v-model:value="formData.username" placeholder="请输入用户名" />
          </n-form-item>
          
          <n-form-item label="邮箱" path="email">
            <n-input v-model:value="formData.email" placeholder="请输入邮箱地址" />
          </n-form-item>
          
          <n-form-item label="手机号" path="phone">
            <n-input v-model:value="formData.phone" placeholder="请输入手机号" />
          </n-form-item>
          
          <n-form-item label="部门" path="department">
            <n-select 
              v-model:value="formData.department"
              :options="departmentOptions"
              placeholder="请选择部门"
            />
          </n-form-item>
          
          <n-form-item label="个人简介" path="bio">
            <n-input 
              v-model:value="formData.bio"
              type="textarea"
              :rows="4"
              placeholder="介绍一下自己吧..."
            />
          </n-form-item>
          
          <n-form-item>
            <n-space>
              <n-button type="primary" @click="handleSaveProfile">
                <template #icon>
                  <n-icon><SaveOutline /></n-icon>
                </template>
                保存信息
              </n-button>
              <n-button @click="resetForm">重置</n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </n-card>
      
      <!-- 密码修改 -->
      <n-card title="密码修改" class="password-section">
        <n-form 
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-placement="left"
          label-width="100px"
        >
          <n-form-item label="当前密码" path="currentPassword">
            <n-input 
              v-model:value="passwordForm.currentPassword"
              type="password"
              show-password-on="click"
              placeholder="请输入当前密码"
            />
          </n-form-item>
          
          <n-form-item label="新密码" path="newPassword">
            <n-input 
              v-model:value="passwordForm.newPassword"
              type="password"
              show-password-on="click"
              placeholder="请输入新密码"
            />
          </n-form-item>
          
          <n-form-item label="确认密码" path="confirmPassword">
            <n-input 
              v-model:value="passwordForm.confirmPassword"
              type="password"
              show-password-on="click"
              placeholder="请再次输入新密码"
            />
          </n-form-item>
          
          <n-form-item>
            <n-button type="warning" @click="handleChangePassword">
              <template #icon>
                <n-icon><KeyOutline /></n-icon>
              </template>
              修改密码
            </n-button>
          </n-form-item>
        </n-form>
      </n-card>
    </div>
    
    <!-- 头像上传弹窗 -->
    <n-modal v-model:show="showAvatarUpload" preset="card" title="上传头像" style="width: 600px;">
      <div class="avatar-upload-container">
        <div class="upload-area" @click="triggerFileInput">
          <input 
            ref="fileInput"
            type="file"
            accept="image/*"
            @change="handleFileSelect"
            style="display: none;"
          />
          
          <div v-if="!previewImage" class="upload-placeholder">
            <n-icon size="48"><CloudUploadOutline /></n-icon>
            <p>点击或拖拽图片到此处</p>
            <p class="upload-tip">支持 JPG、PNG 格式，建议尺寸 200x200</p>
          </div>
          
          <div v-else class="image-preview">
            <img :src="previewImage" alt="预览" />
          </div>
        </div>
        
        <div v-if="previewImage" class="crop-controls">
          <n-slider 
            v-model:value="cropScale"
            :min="0.5"
            :max="2"
            :step="0.1"
            :tooltip="false"
          />
          <p>缩放: {{ (cropScale * 100).toFixed(0) }}%</p>
        </div>
        
        <div class="upload-actions">
          <n-button @click="showAvatarUpload = false">取消</n-button>
          <n-button 
            v-if="previewImage"
            type="primary"
            @click="handleAvatarUpload"
          >
            确认上传
          </n-button>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useMessage } from 'naive-ui'
import {
  CameraOutline,
  CloudUploadOutline,
  SaveOutline,
  KeyOutline
} from '@vicons/ionicons5'
import { useAuthStore } from '@/store'

const message = useMessage()
const authStore = useAuthStore()

const userInfo = computed(() => authStore.userInfo)
const avatarShape = ref<'circle' | 'square'>('circle')
const showAvatarUpload = ref(false)
const previewImage = ref('')
const cropScale = ref(1)
const fileInput = ref<HTMLInputElement>()

const formRef = ref()
const passwordFormRef = ref()

const formData = reactive({
  username: userInfo.value.username || '',
  email: userInfo.value.email || '',
  phone: userInfo.value.phone || '',
  department: userInfo.value.department || '',
  bio: userInfo.value.bio || ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const departmentOptions = [
  { label: '技术部', value: 'tech' },
  { label: '产品部', value: 'product' },
  { label: '运营部', value: 'operation' },
  { label: '市场部', value: 'marketing' },
  { label: '人事部', value: 'hr' },
  { label: '财务部', value: 'finance' }
]

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { 
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, 
      message: '请输入有效的邮箱地址', 
      trigger: 'blur' 
    }
  ],
  phone: [
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入有效的手机号', 
      trigger: 'blur' 
    }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string) => {
        if (value !== passwordForm.newPassword) {
          return new Error('两次输入的密码不一致')
        }
        return true
      },
      trigger: 'blur'
    }
  ]
}

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return
  
  const reader = new FileReader()
  reader.onload = (e) => {
    previewImage.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
}

const handleAvatarUpload = () => {
  // 这里应该调用实际的上传API
  message.success('头像上传成功！')
  showAvatarUpload.value = false
  previewImage.value = ''
}

const handleSaveProfile = async () => {
  try {
    await formRef.value?.validate()
    // 这里应该调用实际的保存API
    message.success('个人信息保存成功！')
  } catch (error) {
    message.error('请检查表单信息')
  }
}

const handleChangePassword = async () => {
  try {
    await passwordFormRef.value?.validate()
    // 这里应该调用实际的密码修改API
    message.success('密码修改成功！')
    Object.assign(passwordForm, {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    message.error('请检查密码信息')
  }
}

const resetForm = () => {
  Object.assign(formData, {
    username: userInfo.value.username || '',
    email: userInfo.value.email || '',
    phone: userInfo.value.phone || '',
    department: userInfo.value.department || '',
    bio: userInfo.value.bio || ''
  })
}
</script>

<style scoped>
.profile-container {
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-header {
  margin-bottom: 32px;
  text-align: center;
}

.profile-header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(135deg, #ff006e, #8338ec);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.profile-header p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.avatar-section .avatar-container {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar-preview {
  position: relative;
  width: 120px;
  height: 120px;
}

.avatar-img, .avatar-placeholder {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  font-weight: 600;
  color: white;
  background: linear-gradient(135deg, #ff006e, #8338ec);
}

.avatar-img.circle, .avatar-placeholder.circle {
  border-radius: 50%;
}

.avatar-img.square, .avatar-placeholder.square {
  border-radius: 12px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
  border-radius: inherit;
}

.avatar-preview:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay n-icon {
  color: white;
}

.avatar-controls {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #8338ec;
  background: rgba(131, 56, 236, 0.05);
}

.upload-placeholder {
  color: #999;
}

.upload-placeholder p {
  margin: 16px 0 0 0;
}

.upload-tip {
  font-size: 12px;
  color: #ccc;
}

.image-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
}

.crop-controls {
  margin: 20px 0;
  text-align: center;
}

.crop-controls p {
  margin: 8px 0 0 0;
  color: #666;
  font-size: 14px;
}

.upload-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }
  
  .avatar-container {
    flex-direction: column;
    text-align: center;
  }
  
  .avatar-controls {
    width: 100%;
  }
}

/* 暗色主题适配 */
:global(.dark) .profile-header h1 {
  background: linear-gradient(135deg, #06ffa5, #26cf6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

:global(.dark) .profile-header p {
  color: #ccc;
}

:global(.dark) .upload-area {
  border-color: #444;
  background: rgba(255, 255, 255, 0.02);
}

:global(.dark) .upload-area:hover {
  border-color: #06ffa5;
  background: rgba(6, 255, 165, 0.05);
}
</style> 